package org.breathe.server.core.impl;

import lombok.Setter;
import org.breathe.database.RedisDB;
import org.breathe.datastruct.RedisBytes;
import org.breathe.datastruct.RedisData;
import org.breathe.server.RedisServer;
import org.breathe.server.core.RedisCore;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: breathe
 * @createTime: 2025-05-12
 */
public class RedisCoreImpl implements RedisCore {
    private final List<RedisDB> databases;
    private final int dbNum;
    private RedisServer server;
    @Setter
    private int currentDbIndex;
    public RedisCoreImpl(int dbNum, RedisServer server) {
        this.dbNum = dbNum;
        this.server = server;
        this.databases = new ArrayList<>(dbNum);
        for (int i = 0; i < dbNum; i ++) {
            databases.add(new RedisDB(i));
        }
    }
    @Override
    public Set<RedisBytes> keys() {
        return getCurrentDb().keys();
    }

    @Override
    public void put(RedisBytes key, RedisData value) {
        getCurrentDb().put(key, value);
    }

    @Override
    public RedisData get(RedisBytes key) {
        return getCurrentDb().get(key);
    }

    @Override
    public void remove(RedisBytes key) {
        getCurrentDb().remove(key);
    }

    @Override
    public void selectDB(int dbIndex) {
        if (dbIndex >= 0 && dbIndex < dbNum) {
            currentDbIndex = dbIndex;
        } else {
            throw new RuntimeException("dbIndex out of range");
        }
    }

    @Override
    public int getDBNum() {
        return dbNum;
    }


    @Override
    public int getCurrentDbIndex() {
        return currentDbIndex;
    }
    private RedisDB getCurrentDb() {
        return databases.get(getCurrentDbIndex());
    }

    @Override
    public RedisDB[] getDatabases() {
        return databases.toArray(new RedisDB[0]);
    }

    @Override
    public RedisServer getServer() {
        return server;
    }
}
